package com.rdgzs.base.listener;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;

import com.rdgzs.framework.utilsTools.ConfigPropertiesUtils;
import com.rdgzs.framework.utilsTools.SqlConfigUtils;

public class ConfigLoaderListener extends ContextLoaderListener implements ServletContextListener {
	private static final Logger log = Logger.getLogger(ConfigLoaderListener.class);
	
	public void contextDestroyed(ServletContextEvent event) {
		
	}
	
	/**
	 * servlet 初始化
	 */
	public void contextInitialized(ServletContextEvent event) {
		if (log.isDebugEnabled()) {
			log.debug("initializing context...");
		}
		try {
			readConfigProperties(event);
			readSqlConfigProperties(event);
			readDictionary(event);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 读取业务的配置文件
	 * 
	 * @param event
	 * @throws Exception
	 */
	public void readConfigProperties(ServletContextEvent event) throws Exception {
		try {
			ConfigPropertiesUtils.configProperties = getPropertiesByFileName("config.properties");
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}
	
	/**
	 * 读取sql配置文件
	 * @param event
	 * @throws Exception
	 */
	public void readSqlConfigProperties(ServletContextEvent event) throws Exception {
		try {
			Properties sqlProperties = new Properties();
			ConfigPropertiesUtils.configProperties = getPropertiesByFileName("config.properties");
			String sqlConfigFiles = (String) ConfigPropertiesUtils.configProperties.get("sqlConfigFiles");
			
			if (StringUtils.isNotBlank(sqlConfigFiles)) {
				String[] sqlConfigArray = sqlConfigFiles.split(",");
				for (int i = 0; i < sqlConfigArray.length; i++) {
					Properties sqlPro = getPropertiesByFileName(sqlConfigArray[i] + ".properties");
					sqlProperties.putAll(sqlPro);
				}
			} else {
				throw new Exception("config 内sql配置文件列表为空！");
			}
			SqlConfigUtils.sqlProperties = sqlProperties;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}
	
	/**
	 * 根椐文件名得到资源文件
	 * 
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public Properties getPropertiesByFileName(String fileName) throws Exception {
		Properties configProperties = new Properties();
		try {
			URL url = ConfigLoaderListener.class.getClassLoader().getResource("");
			String uri = url.getFile() + fileName;
			File file = new File(uri);
			if (file.exists()) {
				InputStream in = new BufferedInputStream(new FileInputStream(uri));
				configProperties.load(in);
			} else {
				System.out.print("目标配置文件不存在！");
			}
			
			return configProperties;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}
	
	/**
	 * 读取业务的配置文件
	 * 
	 * @param event
	 */
	public void readDictionary(ServletContextEvent event) {
	/**	Map dictionaryMap = new HashMap();
		//ServletContext context = event.getServletContext();
		WebApplicationContext applicationContext = ContextLoader.getCurrentWebApplicationContext();
		//ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
		
		DictionaryManager dictManager = (DictionaryManager) applicationContext.getBean("dictionaryManager");
		List<SysDictionary> dictTypeList = dictManager.getAllDictType();
		for (SysDictionary type : dictTypeList) {
			if(type!=null){
				List<SysDictionary> dictdateList = dictManager.getDictData(type.getId());//这么写是因为dictType此时不存在sesson
				dictionaryMap.put(type.getParamCode(), dictdateList);
			}
		}
		DictionaryUtils.dictMap = dictionaryMap; **/
	}
	
	/**
	 * 读取xml文件
	 * 
	 * @param event
	 */
	public void readSqlConfigXml(ServletContextEvent event) {
		try {
			Map sqlMap = new HashMap();
			SAXReader reader = new SAXReader();
			URL url = ConfigLoaderListener.class.getClassLoader().getResource("");
			String uri = url.getFile() + "SqlConfig.xml";
			// InputStream in =
			// event.getServletContext().getResourceAsStream("SqlConfig.xml");
			// Document document = reader.read(new File(uri));
			Document document = reader.read(new File(uri));
			Element rootElm = document.getRootElement();
			// 取得当前文件里的所有结点
			for (Iterator nodeIt = rootElm.elementIterator(); nodeIt.hasNext();) {
				Element node = (Element) nodeIt.next();
				String nodeName = node.getName();
				// 验证所有的结点应该为sql
				if (StringUtils.isNotBlank(nodeName) && (nodeName.toLowerCase().equals("sql"))) {
					if (node.attributeCount() > 0) {
						boolean hasKey = false;
						Iterator attrIt1 = node.attributeIterator();
						// 验证所有结点属性是否包含有key的属性
						for (Iterator attrIt = node.attributeIterator(); attrIt.hasNext();) {
							Attribute attr = (Attribute) attrIt.next();
							if (attr.getName().equals("key")) {
								hasKey = true;
								// attr.setName("aa");
								// attr.setValue(attr.getName().toLowerCase());
								break;
							}
						}
						if (hasKey) {
							// 结点内容不可以空
							if (node.getText().trim().length() > 0) {
								sqlMap.put(node.attributeValue("key"), node.getText());
							} else {
								throw new Exception("SQL配置文件元素异常:元素结点内容不可以为空\n" + node.getText());
							}
						} else {
							throw new Exception("SQL配置文件元素异常:元素结点缺少key属性\n" + node.getText());
						}
					}
				} else {
					throw new Exception("SQL配置文件元素异常:元素应为sql\n" + node.getText());
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
